#include <vector>
#include <queue>

using std::queue;
using std::vector;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> q;
        vector<vector<int>> ret;
        if (root != nullptr) {
            q.push(root);
        }
        int count = 1;
        TreeNode* tmp;
        vector<int> v;
        while (!q.empty()) {
            tmp = q.front();
            q.pop();
            if (tmp->left != nullptr) {
                q.push(tmp->left);
            }
            if (tmp->right != nullptr) {
                q.push(tmp->right);
            }
            count--;
            v.push_back(tmp->val);
            if (count == 0) {
                count = q.size();
                ret.push_back(v);
                if (count > 0) {
                    v = vector<int>();
                }
            }
        }
        return ret;
    }
};